package com.megastudyletsthi;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.hocmai.json.request.SendJsonSignIn;

public class HocmaiSignInActivity extends Activity {

	EditText signName, signPass, reSignPass, signDateBorn, signPhone;
	Button signIn;
	Spinner spinSex;
	private static final String URL_SIGN_IN = "http://megatest.com.vn/user_sign_in.php"; // set
																							// URL_SIGN_IN
	// JSON data node
	private static final String TAG_SIGN_IN = "sign";
	private static final String TAG_SIGNAL = "signal";

	String signal = null;
	String sex = null;

	ProgressDialog progressDialog;
	JSONArray sign = null;
	// Send Json Data To Sever
	SendJsonSignIn sendJsonSignIn = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin_layout);

		signName = (EditText) findViewById(R.id.insert_name);
		signPass = (EditText) findViewById(R.id.insert_pass);
		reSignPass = (EditText) findViewById(R.id.reinsert_pass);
		signDateBorn = (EditText) findViewById(R.id.date_born);
		signPhone = (EditText) findViewById(R.id.insert_phone_number);
		signIn = (Button) findViewById(R.id.sign_in);
		spinSex = (Spinner) findViewById(R.id.sex);
		// /////////////////////////////////////////////////
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.sex, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinSex.setAdapter(adapter);
		spinSex.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int pos, long arg3) {
				sex = parent.getItemAtPosition(pos).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		// //////////////////////////////////////////////////////
		signIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String id = signName.getText().toString();
				String pass = signPass.getText().toString();
				String rePass = reSignPass.getText().toString();
				String dateBorn = signDateBorn.getText().toString();
				String phone = signPhone.getText().toString();

				if (!rePass.equals(pass)) {
					Toast.makeText(HocmaiSignInActivity.this,
							"Nhập PassWord chưa trùng nhau!", Toast.LENGTH_LONG)
							.show();
				} else if (id.length() == 0 || pass.length() == 0
						|| rePass.length() == 0 || dateBorn.length() == 0
						|| phone.length() == 0) {
					Toast.makeText(HocmaiSignInActivity.this,
							"Bạn chưa hoàn thành tất cả các mục",
							Toast.LENGTH_LONG).show();

				} else if (rePass.equals(pass) && isOnline() == true) {
					progressDialog = new ProgressDialog(
							HocmaiSignInActivity.this);
					progressDialog.setTitle("Xin chờ !");
					progressDialog.setMessage("Đang gửi đang ký !");
					progressDialog.show();
					new Asyn().execute("1");
				} else {
					Toast.makeText(HocmaiSignInActivity.this,
							"Lỗi kết nối tới máy chủ", Toast.LENGTH_LONG)
							.show();
				}
			}
		});
	}

	// check connect to internet.
	public boolean isOnline() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		return (networkInfo != null && networkInfo.isConnected());
	}

	/*
	 * get signal sign in
	 */
	class Asyn extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String id = signName.getText().toString();
			String pass = signPass.getText().toString();
			String dateBorn = signDateBorn.getText().toString();
			String phone = signPhone.getText().toString();

			MD5 md5 = new MD5();
			sendJsonSignIn = new SendJsonSignIn();
			try {
				if (sex.equals("Nam")) {
					sendJsonSignIn.sendJsonSignIn(id, md5.getMD5(pass), "1", dateBorn,
							phone, URL_SIGN_IN);
				} else if (sex.equals("Nữ")) {
					sendJsonSignIn.sendJsonSignIn(id, md5.getMD5(pass), "0", dateBorn,
							phone, URL_SIGN_IN);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			// ////////////////////////////////
			checkSignIn();
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			if (signal.equals("1")) {
				Toast.makeText(HocmaiSignInActivity.this,
						"Đăng ký thành công !", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(HocmaiSignInActivity.this,
						HocmaiLoginActivity.class);
				startActivity(intent);
			} else if (signal.equals("0")) {
				Toast.makeText(HocmaiSignInActivity.this,
						"Tài khoản đã tồn tại !", Toast.LENGTH_LONG).show();
			}
		}
	}

	public void checkSignIn() {
		try {
			// Parse the data into jsonobject to get original data in form of
			// json.
			JSONObject jObject = new JSONObject(sendJsonSignIn.DATA);
			JSONArray jArray = jObject.getJSONArray(TAG_SIGN_IN);
			// ArrayList<String[]> data = new ArrayList<String[]>();
			for (int i = 0; i < jArray.length(); i++) {
				signal = jArray.getJSONObject(i).getString(TAG_SIGNAL);
				if (signal.equals("1")) {
					// Chuyển sang màn hình login
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
